package com.controller;

import com.model.operation.UserOperate;
import net.sf.json.JSONObject;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;

/**
 * Created by LPFma on 2016/12/3 0003.
 */
@WebServlet(name = "UserLoginControl", urlPatterns = "/UserLogin")
public class UserLoginControl extends HttpServlet {

    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        /*init response*/
        response.setCharacterEncoding("UTF-8");
        response.setContentType("application/json; charset=utf-8");
        response.addHeader("Access-Control-Allow-Origin","*");
        response.addHeader("Access-Control-Allow-Credentials", "true");
        response.addHeader("Access-Control-Allow-Methods", "GET, POST, PUT, DELETE, OPTIONS");

        /*post arguments*/
        String username = request.getParameter("username");
        String passwd = request.getParameter("passwd");
        String status;

        String user = (String) request.getSession().getAttribute("username");

        System.out.println("username: " + username + " user: " + user);
        if (user != null && username.equals(user)) {
            status = "hello";
        } else {
            /* check if user valid */
            UserOperate userOperate = new UserOperate();
            status = userOperate.IsUserValid(username, passwd);

            if (status.equals("success")) {
                Cookie cookie = new Cookie("username", username);
                cookie.setMaxAge(7 * 24 * 60 * 60);
                response.addCookie(cookie);
                request.setAttribute("username", username);
                request.getSession().setAttribute("username", username);
            }
        }

        String finalStatus = status;
        Map map = new HashMap<String, String>() {{
            put("status", finalStatus);
        }};

        /* send json */
        JSONObject jsonObject = JSONObject.fromObject(map);
        response.getWriter().write(jsonObject.toString());
    }

    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {

    }
}
